#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <fstream>
#include <cassert>
#include "util.hpp"




class UDPServer
{
public:
    UDPServer(int port,int buffer_size,std::string log_path) : port(port),buffer_size(buffer_size),sockfd(-1)
    {
        memset(&servaddr, 0, sizeof(servaddr));
        memset(&cliaddr, 0, sizeof(cliaddr));
        ofs.open(log_path);
        assert(ofs.is_open());
    }

    ~UDPServer()
    {
        if (sockfd != -1)
        {
            close(sockfd);
        }
    }

    bool start()
    {
        // 创建 socket
        if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
        {
            perror("socket creation failed");
            return false;
        }

        // 填充服务端信息
        servaddr.sin_family = AF_INET; // IPv4
        servaddr.sin_addr.s_addr = INADDR_ANY;
        servaddr.sin_port = htons(port);

        // 绑定 socket
        if (bind(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
        {
            perror("bind failed");
            close(sockfd);
            sockfd = -1;
            return false;
        }
        return true;
    }

    void run()
    {
        while (true)
        {
            receiveMessage();
            sleep(1);
        }
    }

private:
    void receiveMessage()
    {
        char buffer[buffer_size];
        socklen_t len = sizeof(cliaddr);
        int n = recvfrom(sockfd, buffer, buffer_size, MSG_WAITALL, (struct sockaddr *)&cliaddr, &len);
        //发送确认应答
        sendto(sockfd,ack,strlen(ack),MSG_CONFIRM,(struct sockaddr *)&cliaddr,len);
        buffer[n] = '\0';
        ofs.write(buffer,n);
        ofs.flush();
    }

private:
    int port;
    int sockfd;
    int buffer_size;
    const char* ack="ok";//确认应答信息
    std::ofstream ofs;
    
    struct sockaddr_in servaddr, cliaddr;
};

